import { createSlice, PayloadAction } from "@reduxjs/toolkit";

export type TodoItemType = {
  id: string;
  title: string;
  completed: boolean;
};

const INIT_STATE: TodoItemType[] = [
  {
    id: Date.now() + "",
    title: "吃饭",
    completed: false,
  },
];

export const todoSlice = createSlice({
  name: "todoList",
  initialState: INIT_STATE,
  reducers: {
    addTodo(state: TodoItemType[], action: PayloadAction<TodoItemType>) {
      return [
        action.payload, // 添加的todo
        ...state,
      ];
    },
    delTodo(state: TodoItemType[], action: PayloadAction<{ id: string }>) {
      return state.filter((item) => item.id !== action.payload.id);
    },
    toggleTodo(state: TodoItemType[], action: PayloadAction<{ id: string }>) {
      return state.map((item) => {
        if (item.id === action.payload.id) {
          return {
            ...item,
            completed: !item.completed,
          };
        }
        return item;
      });
    },
  },
});

export const { addTodo, delTodo, toggleTodo } = todoSlice.actions;

export default todoSlice.reducer;
